package services;

import helpers.ConsoleConstants;
import helpers.ConsoleUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import play.Logger;

import controllers.TestSuites;

import models.Company;
import models.Project;
import models.Resource;
import models.ResourceType;
import models.Setting;

/**
 * SynchronizationService It loads all projects from robot framework directory and checks agains console database. If the console db does not have entry of the project, it will create one. If the console db does have the project entry, it will update lastModified date If there are files insides the project directory, it will consider as test suites
 * 
 * It also synchronize configurations and resources
 * 
 * 
 */
public class SynchronizationService {

	private final TestResourceService resourceService = TestResourceService.getService();

	private final ConfigurationService configService = ConfigurationService.getService();
	private final ProjectService projectService = ProjectService.getService();
	// private final ReportService reportService = ReportService.getService();
	private final SettingService settingService = SettingService.getService();
	private final TestSuiteService testSuiteService = TestSuiteService.getService();
	private final TestCaseService testCaseService = TestCaseService.getService();

	private final SimpleDateFormat synchonizationDateFormat = new SimpleDateFormat("yyMMddHHmmss");

	private static SynchronizationService service;

	// Singleton pattern
	private SynchronizationService() {
	}

	public static SynchronizationService getService() {
		if (service == null) {
			service = new SynchronizationService();
		}
		return service;
	}

	public void synchronizeResources(Company company) {
		if (company != null) {
			synchronizeCommonConfigurations(company);
			synchronizeCommonResources(company);
			synchronizeProjects(company);
		}
	}

	public void synchronizeCommonConfigurations(final Company company) {
		final File synchronizeDirectory = new File(getSynchronizeConfigDirectory(company));
		final String[] configFileNames = getFiles(synchronizeDirectory);
		if (configFileNames == null || configFileNames.length == 0) {
			return; // No config found
		}
		final File synchronizedDirectory = new File(getSynchronizedConfigDirectory(company));
		boolean synchronizationSuccessfully;
		File configFile;
		for (String configFileName : configFileNames) {
			if (configFileName.endsWith(ConfigurationService.CONFIG_FILE_EXTENSION)) {
				configFile = new File(synchronizeDirectory, configFileName);
				synchronizationSuccessfully = synchronizeCommonConfig(company, configFile);
				try {
					if (synchronizationSuccessfully) {
						FileUtils.moveFile(configFile, new File(synchronizedDirectory, configFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_SUCCESSFUL_DIRECTORY_SUFFIX));
					} else {
						FileUtils.moveFile(configFile, new File(synchronizedDirectory, configFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_FAILED_DIRECTORY_SUFFIX));
					}
					Logger.info("Synchronizing configuration " + company.getCompanyId() + ":" + configFileName + " " + isSuccess(synchronizationSuccessfully) + "!");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void synchronizeCommonResources(final Company company) {
		final File synchronizeDirectory = new File(getSynchronizeResourceDirectory(company));
		final String[] resourceFileNames = getFiles(synchronizeDirectory);
		if (resourceFileNames == null || resourceFileNames.length == 0) {
			return; // No resource found
		}
		final File synchronizedDirectory = new File(getSynchronizedResourceDirectory(company));
		boolean synchronizationSuccessfully;
		File resourceFile;
		for (String configFileName : resourceFileNames) {
			if (configFileName.endsWith(TestResourceService.RESOURCE_FILE_EXTENSION)) {
				resourceFile = new File(synchronizeDirectory, configFileName);
				synchronizationSuccessfully = synchronizeCommonResource(company, resourceFile);
				try {
					if (synchronizationSuccessfully) {
						FileUtils.moveFile(resourceFile, new File(synchronizedDirectory, resourceFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_SUCCESSFUL_DIRECTORY_SUFFIX));
					} else {
						FileUtils.moveFile(resourceFile, new File(synchronizedDirectory, resourceFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_FAILED_DIRECTORY_SUFFIX));
					}
					Logger.info("Synchronizing resource " + company.getCompanyId() + ":" + configFileName + " " + isSuccess(synchronizationSuccessfully) + "!");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Synchronize resource in global common directory
	 */
	public void synchronizeGlobalResources() {
		final File synchronizeDirectory = new File(getSynchronizeGlobalResourceDirectory());
		final String[] resourceFileNames = getFiles(synchronizeDirectory);
		if (resourceFileNames == null || resourceFileNames.length == 0) {
			return; // No resource found
		}
		final File synchronizedDirectory = new File(getSynchronizedGlobalResourceDirectory());
		boolean synchronizationSuccessfully;
		File resourceFile;
		for (String configFileName : resourceFileNames) {
			if (configFileName.endsWith(TestResourceService.RESOURCE_FILE_EXTENSION)) {
				resourceFile = new File(synchronizeDirectory, configFileName);
				synchronizationSuccessfully = synchronizeCommonResource(resourceFile);
				try {
					if (synchronizationSuccessfully) {
						FileUtils.moveFile(resourceFile, new File(synchronizedDirectory, resourceFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_SUCCESSFUL_DIRECTORY_SUFFIX));
					} else {
						FileUtils.moveFile(resourceFile, new File(synchronizedDirectory, resourceFile.getName() + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_FAILED_DIRECTORY_SUFFIX));
					}
					Logger.info("Synchronizing resource global:" + configFileName + " " + isSuccess(synchronizationSuccessfully) + "!");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Global resource synchronize directory which can be used for every company
	 * 
	 * @return
	 */
	private String getSynchronizeGlobalResourceDirectory() {
		String directory = null;
		final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
		if (setting != null) {
			directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), ConsoleConstants.COMMON_DIRECTORY, ConsoleConstants.SYNCHRONIZE_DIRECTORY, ConsoleConstants.RESOURCES_DIRECTORY });
		}
		return directory;
	}

	/**
	 * Global resource synchronized directory
	 * 
	 * @return
	 */
	private String getSynchronizedGlobalResourceDirectory() {
		String directory = null;
		final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
		if (setting != null) {
			directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), ConsoleConstants.COMMON_DIRECTORY, ConsoleConstants.SYNCHRONIZED_DIRECTORY, ConsoleConstants.RESOURCES_DIRECTORY });
		}
		return directory;
	}

	private String getSynchronizeResourceDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZE_DIRECTORY, ConsoleConstants.RESOURCES_DIRECTORY });
			}
		}
		return directory;
	}

	private String getSynchronizedResourceDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZED_DIRECTORY, ConsoleConstants.RESOURCES_DIRECTORY });
			}
		}
		return directory;
	}

	private String getSynchronizeConfigDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZE_DIRECTORY, ConsoleConstants.CONFIGURATION_DIRECTORY });
			}
		}
		return directory;
	}

	private String getSynchronizedConfigDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZED_DIRECTORY, ConsoleConstants.CONFIGURATION_DIRECTORY });
			}
		}
		return directory;
	}

	private boolean synchronizeCommonConfig(final Company company, final File configFile) {
		boolean result = false;
		if (company != null && configFile != null) {
			try {
				String name = configFile.getName();
				if (name.endsWith(ConfigurationService.CONFIG_FILE_EXTENSION)) {
					name = name.substring(0, name.length() - ConfigurationService.CONFIG_FILE_EXTENSION.length());
				}
				final String content = ConsoleUtils.getFileContent(configFile);
				Resource config = configService.getConfig(company, name);
				if (config == null) {
					config = new Resource(ResourceType.TestConfiguration, company, name);
					config.setDescription("Synchronized " + company.getCompanyId() + " configuration");
				}
				config = configService.saveConfig(company, config, content);
				result = config.getId() > 0;
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	/**
	 * Synchronize global resource which can be used for any company
	 * 
	 * @param resourceFile
	 * @return
	 */
	private boolean synchronizeCommonResource(final File resourceFile) {
		boolean result = false;
		if (resourceFile != null) {
			try {
				String name = resourceFile.getName();
				if (name.endsWith(TestResourceService.RESOURCE_FILE_EXTENSION)) {
					name = name.substring(0, name.length() - TestResourceService.RESOURCE_FILE_EXTENSION.length());
				}
				final String content = ConsoleUtils.getFileContent(resourceFile);
				Resource resource = resourceService.getResource(name);
				if (resource == null) {
					resource = new Resource(ResourceType.TestResource, name);
					resource.setDescription("Synchronized global resource");
				}
				resource = resourceService.saveResource(resource, null, content);
				result = resource.getId() > 0;
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	/**
	 * Synchronize common resource for a company
	 * 
	 * @param company
	 * @param resourceFile
	 * @return
	 */
	private boolean synchronizeCommonResource(final Company company, final File resourceFile) {
		boolean result = false;
		if (company != null && resourceFile != null) {
			try {
				String name = resourceFile.getName();
				if (name.endsWith(TestResourceService.RESOURCE_FILE_EXTENSION)) {
					name = name.substring(0, name.length() - TestResourceService.RESOURCE_FILE_EXTENSION.length());
				}
				final String content = ConsoleUtils.getFileContent(resourceFile);
				Resource resource = resourceService.getResource(company, name);
				if (resource == null) {
					resource = new Resource(ResourceType.TestResource, company, name);
					resource.setDescription("Synchronized " + company.getCompanyId() + " resource");
				}
				resource = resourceService.saveResource(company, resource, null, content);
				result = resource.getId() > 0;
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	public void synchronizeProjects(final Company company) {
		final File synchronizeDirectory = new File(getSynchronizeProjectDirectory(company));
		final String[] projectNames = getSubDirectories(synchronizeDirectory);
		if (projectNames == null || projectNames.length == 0) {
			return; // No projects found
		}
		final File synchronizedDirectory = new File(getSynchronizedProjectDirectory(company));
		boolean synchronizedSuccessfully;
		File projectDirectory;
		for (String projectName : projectNames) {
			Project existingProject = projectService.getProject(company.getId(), projectName);
			projectDirectory = new File(synchronizeDirectory, projectName);
			synchronizedSuccessfully = synchronizeProject(company, projectDirectory, existingProject);
			try {
				if (synchronizedSuccessfully) {
					FileUtils.moveDirectoryToDirectory(projectDirectory, new File(synchronizedDirectory, projectName + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_SUCCESSFUL_DIRECTORY_SUFFIX), true);
				} else {
					FileUtils.moveDirectoryToDirectory(projectDirectory, new File(synchronizedDirectory, projectName + "-" + synchonizationDateFormat.format(new Date()) + ConsoleConstants.SYNCHRONIZED_FAILED_DIRECTORY_SUFFIX), true);
				}
				Logger.info("Synchronizing project " + company.getCompanyId() + ":" + projectName + " " + isSuccess(synchronizedSuccessfully) + "!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private boolean synchronizeProject(final Company company, final File projectDirectory, final Project existingProject) {
		boolean result = false;
		if (company != null) {
			Project project = existingProject;
			try {
				if (project == null) {
					project = new Project(company, projectDirectory.getName());
					project.setDescription("Synchronized project");
				}
				project = projectService.saveProject(project);

				if (project.getId() > 0) {
					result = synchronizeConfig(project, projectDirectory);
					result = synchronizeResource(project, projectDirectory);
					result = synchronizeTestSuites(project, projectDirectory);
				}
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	private boolean synchronizeConfig(Project project, File projectDirectory) {
		boolean result = true;
		final File projectConfigDirectory = new File(projectDirectory, ConsoleConstants.CONFIGURATION_DIRECTORY);
		final String[] projectConfigFiles = getFiles(projectConfigDirectory);
		if (projectConfigFiles != null && projectConfigFiles.length > 0) {
			for (String projectConfigFile : projectConfigFiles) {
				if (!synchronizeProjectConfig(project, new File(projectConfigDirectory, projectConfigFile))) {
					result = false;
					Logger.info("Synchronizing configuration " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + projectConfigFile + " " + isSuccess(result) + "!");
					break;
				}
				Logger.info("Synchronizing configuration " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + projectConfigFile + " " + isSuccess(result) + "!");
			}
		}
		return result;
	}

	private boolean synchronizeResource(Project project, File projectDirectory) {
		boolean result = true;
		final File projectTestResourceDirectory = new File(projectDirectory, ConsoleConstants.RESOURCES_DIRECTORY);
		final String[] projectTestResourceFiles = getFiles(projectTestResourceDirectory);
		if (projectTestResourceFiles != null && projectTestResourceFiles.length > 0) {
			for (String projectTestResourceFile : projectTestResourceFiles) {
				if (!synchronizeProjectResource(project, new File(projectTestResourceDirectory, projectTestResourceFile))) {
					result = false;
					Logger.info("Synchronizing resource " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + projectTestResourceFile + " " + isSuccess(result) + "!");
					break;
				}
				Logger.info("Synchronizing resource " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + projectTestResourceFile + " " + isSuccess(result) + "!");
			}
		}
		return result;
	}

	private boolean synchronizeProjectConfig(Project project, File configFile) {
		boolean result = false;
		if (configFile != null) {
			try {
				String name = configFile.getName();
				if (name.endsWith(ConfigurationService.CONFIG_FILE_EXTENSION)) {
					name = name.substring(0, name.length() - ConfigurationService.CONFIG_FILE_EXTENSION.length());
				}
				final String content = ConsoleUtils.getFileContent(configFile);
				Resource config = configService.getConfig(project, name);
				if (config == null) {
					config = new Resource(ResourceType.TestConfiguration, project, name);
					config.setDescription("Synchronized project " + project.getName() + " configuration");
				}
				config = configService.saveConfig(project, config, content);
				result = config.getId() > 0;
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	private boolean synchronizeProjectResource(Project project, File testResourceFile) {
		boolean result = false;
		if (testResourceFile != null) {
			try {
				String name = testResourceFile.getName();
				if (name.endsWith(TestResourceService.RESOURCE_FILE_EXTENSION)) {
					name = name.substring(0, name.length() - TestResourceService.RESOURCE_FILE_EXTENSION.length());
				}
				final String content = ConsoleUtils.getFileContent(testResourceFile);
				Resource config = resourceService.getResource(project, name);
				
				if (config == null) {
					config = new Resource(ResourceType.TestResource, project, name);
					config.setDescription("Synchronized project " + project.getName() + " resource");
				}
				
				config = resourceService.saveResource(project, config, null, content);
				result = config.getId() > 0;
			} catch (Exception e) {
				result = false;
			}
		}
		return result;
	}

	private boolean synchronizeTestSuites(final Project project, final File projectDirectory) {
		boolean result = true;
		final File testSuitesDirectory = new File(projectDirectory, ConsoleConstants.TEST_SUITES_DIRECTORY);
		final String[] testSuiteFiles = getFiles(testSuitesDirectory);
		if (testSuiteFiles != null && testSuiteFiles.length > 0) {
			for (String testSuite : testSuiteFiles) {
				if (!synchronizeTestSuite(project, new File(testSuitesDirectory, testSuite))) {
					result = false;
					Logger.info("Synchronizing test suite " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + testSuite + " " + isSuccess(result) + "!");
					break;
				}
				Logger.info("Synchronizing test suite " + project.getCompany().getCompanyId() + ":" + project.getName() + ":" + testSuite + " " + isSuccess(result) + "!");
			}
		}
		return result;
	}

	private boolean synchronizeTestSuite(final Project project, final File testSuiteFile) {
		boolean result = false;
		if (project != null && project.getId() > 0 && testSuiteFile != null && testSuiteFile.exists()) {
			String name = testSuiteFile.getName();
			if (ConsoleUtils.hasFileExtension(name, TestSuites.TEST_SUITE_FILE_EXTENSIONS)) {
				name = name.substring(0, name.lastIndexOf('.'));
			}
			Resource testSuite = testSuiteService.getTestSuite(project, name);
			if (testSuite == null) {
				testSuite = new Resource(ResourceType.TestSuite, project, name);
				testSuite.setDescription("Synchronized test suite");
			}

			final File testSuiteDirectory = new File(testSuiteService.getTestSuitesDirectory(project));
			if (!testSuiteDirectory.exists()) {
				testSuiteDirectory.mkdirs();
			}
			final File file = new File(testSuiteDirectory.getAbsolutePath(), testSuiteFile.getName());

			try {
				FileUtils.copyFile(testSuiteFile, file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				return false;
			}

			testSuite.setResourcePath(file.getAbsolutePath());
			testSuite = testSuiteService.saveTestSuite(testSuite);

			if (testSuite.getId() > 0) {
				result = synchronizeTestCases(project, testSuite, file);
			}
		}
		return result;
	}

	private String getSynchronizeProjectDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZE_DIRECTORY, ConsoleConstants.PROJECTS_DIRECTORY });
			}
		}
		return directory;
	}

	private String getSynchronizedProjectDirectory(final Company company) {
		String directory = null;
		if (company != null) {
			final Setting setting = settingService.getSetting(Setting.CUSTOMERS_ROOT_DIRECTORY);
			if (setting != null) {
				directory = ConsoleUtils.getPath(new String[] { setting.getStringValue(), company.getCompanyId(), ConsoleConstants.SYNCHRONIZED_DIRECTORY, ConsoleConstants.PROJECTS_DIRECTORY });
			}
		}
		return directory;
	}

	private boolean synchronizeTestCases(final Project project, final Resource testSuite, final File testSuiteFile) {
		boolean result = false;
		if (testSuite != null && testSuite.getId() > 0 && testSuiteFile != null && testSuiteFile.exists() && testSuiteFile.isFile()) {
			if (ConsoleUtils.hasFileExtension(testSuiteFile.getAbsolutePath(), TestSuites.TEST_SUITE_HTML_FILE_EXTENSIONS)) {
				result = synchronizeTestCasesFromHtmlFile(testSuite, testSuiteFile);
			} else if (ConsoleUtils.hasFileExtension(testSuiteFile.getAbsolutePath(), TestSuites.TEST_SUITE_TEXT_FILE_EXTENSIONS)) {
				result = synchronizeTestCasesFromTextFile(testSuite, testSuiteFile);
			}
		}
		return result;
	}

	private boolean synchronizeTestCasesFromHtmlFile(Resource testSuite, File testSuiteFile) {
		boolean result = false;
		try {
			final Document document = Jsoup.parse(testSuiteFile, "UTF-8");
			Elements testCaseTables = document.select("table#testcase"), testCaseLinks;
			for (Element testCaseTable : testCaseTables) {
				testCaseLinks = testCaseTable.select("a[name^=test_]");
				for (Element testCaseLink : testCaseLinks) {
					synchronizeTestCase(testSuite, testCaseLink.text(), testSuiteFile);
				}
			}
			result = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			result = false;
		}
		return result;
	}

	private boolean synchronizeTestCasesFromTextFile(Resource testSuite, File testSuiteFile) {
		boolean result = false;
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(testSuiteFile));

			boolean testCasesSectionOpen = false;
			String line = reader.readLine();
			while (line != null) {
				if (!testCasesSectionOpen && (line.equalsIgnoreCase("*** Test Cases ***") || line.equalsIgnoreCase("*** Test Case ***"))) {
					testCasesSectionOpen = true;
				} else if (testCasesSectionOpen) {
					if (line.startsWith("*** ")) {
						break;
					} else if (line.matches("^\\S.*")) { // Non-whitespace character
						synchronizeTestCase(testSuite, line, testSuiteFile);
					}
				}
				line = reader.readLine();
			}
			result = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			result = false;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
			}
		}
		return result;
	}

	private void synchronizeTestCase(final Resource testSuite, final String testCaseName, final File testSuiteFile) {
		boolean newTestCase = false;
		Resource testCase = testCaseService.getTestCase(testSuite, testCaseName);
		
		if (testCase == null) {
			testCase = new Resource(ResourceType.TestCase, testSuite.getProject(), testCaseName);
			testCase.setDescription("Synchronized test case");
			newTestCase = true;
		}
		
		testCase.setResourcePath(testSuiteFile.getAbsolutePath());
		testCaseService.saveTestCase(testCase);
		
		if (newTestCase) {
			testSuite.addResource(testCase);
			testSuite.save();
		}
	}

	/*
	 * public List<Report> synchronizeReports(Company company) { List<Report> reports = new ArrayList<Report>(); String reportsDirectory = reportService.getCompanyReportsDirectory(company); if (reportsDirectory != null) { reports.addAll(synchronizeCompanyReports(company, reportsDirectory)); } List<Resource> projects = Resource.findProjectsByCompany(company); if (projects != null && projects.size() > 0) { for (Resource project : projects) { reportsDirectory = reportService.getProjectReportsDirectory(company, project.getName()); reports.addAll(synchronizeProjectReports(company, project.getName(), reportsDirectory)); } } return reports; }
	 * 
	 * private List<Report> synchronizeCompanyReports(Company company, String reportsDirectory) { List<Report> reports = new ArrayList<Report>(); String[] reportDirectoryNames = getSubDirectories(new File(reportsDirectory)); if (reportDirectoryNames != null && reportDirectoryNames.length > 0) { Report report; for (String reportDirectoryName : reportDirectoryNames) { report = reportService.createReportModel(company, null, ConsoleUtils.getPath(new String[] { reportsDirectory, reportDirectoryName }), reportDirectoryName); if (report != null) { reports.add(report); } } } return reports; }
	 * 
	 * private List<Report> synchronizeProjectReports(Company company, String projectName, String reportsDirectory) { List<Report> reports = new ArrayList<Report>(); String[] reportDirectoryNames = getSubDirectories(new File(reportsDirectory)); if (reportDirectoryNames != null && reportDirectoryNames.length > 0) { Report report; for (String reportDirectoryName : reportDirectoryNames) { report = reportService.createReportModel(company, projectName, ConsoleUtils.getPath(new String[] { reportsDirectory, reportDirectoryName }), reportDirectoryName); if (report != null) { reports.add(report); } } } return reports; }
	 */

	private String isSuccess(boolean result) {
		if (result)
			return "successful";
		else
			return "failed";
	}

	private String[] getSubDirectories(final File parentDirectory) {
		final String[] directories = parentDirectory.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return new File(dir, name).isDirectory();
			}
		});
		return directories;
	}

	private String[] getFiles(final File directory) {
		final String[] files = directory.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return new File(dir, name).isFile();
			}
		});
		return files;
	}

}
